/* server.js 服务器 */

const pkg = require('./scoket/onmessage')
const {onMessage} = pkg;
const WebSocketServer = require('websocket').server
//const onMessage =require('./scoket/onmessage').onMessage
const http = require('http')

const port = 8800
let time = 0
let socket = []; // 连接的人

// 创建服务器
const server = http.createServer((request, response) => {
    console.log(`${new Date().toLocaleDateString()} Received request for ${request.url}`)
    response.writeHead(404)
    response.end()
})
server.listen(port, () => {
    console.log(`${new Date().toLocaleDateString()} Server is listening on port ${port}`)
})
// websocket 服务器
const wsServer = new WebSocketServer({
    httpServer: server
})
// 建立连接
wsServer.on('request', (request) => {
    // 当前的连接
    console.log(request.origin, '=======request.origin=======')
    const ws = request.accept(null, request.origin)
    console.log(`${new Date().toLocaleDateString()} 已经建立连接`)
    let id = Number(request.resourceURL.query.id)

    socket.push({
        id,
        ws: ws
    })
    setInterval(() => {
        const obj = {
            type: 'system',
            title: '标题' + time++,
            value: '内容' + time++
        }
        ws.send(JSON.stringify(obj))
    }, 25000)

    // 监听客户端发来的的消息
    ws.on('message', (message) => {
        console.log('me0ssage========>', message)
        if (message.type === 'utf8') {
            onMessage(message, ws, id, socket)
            // const data = JSON.parse(message.utf8Data)
            // data.userId = id
            // console.log('Received Message: ' + message.utf8Data);
            // // ws.send(JSON.stringify(data))
            // ws.sendUTF(JSON.stringify(data));

        } else if (message.type === 'binary') {
            // binary 二进制
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            // ws.sendBytes(message.binaryData);
        }
    });

    // 监听当前连接 当断开链接(网页关闭) 触发
    ws.on('close', (reasonCdoe, description) => {
        console.log(`${new Date().toLocaleDateString()} ${ws.remoteAddress} 断开链接`)
    })
})